package org.maven.dependencybrowser.implementations.local;
/**********************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Contributors:

**********************************************************************/
import org.maven.dependencybrowser.implementations.Workspace;
import org.maven.dependencybrowser.implementations.WorkspaceLoader;
import org.maven.dependencybrowser.model.ArtifactInitialisationException;
import org.maven.dependencybrowser.model.RootPom;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;

public class LocalDiskWorkspaceLoader implements WorkspaceLoader
{
    private Workspace workspace;
    private JFrame frame;

    private LocalDiskWorkspace localDiskWorkspace()
    {
        if (workspace instanceof LocalDiskWorkspace)
        {
            return (LocalDiskWorkspace) workspace;
        }
        throw new RuntimeException("Expected workspace of type " + LocalDiskWorkspace.class.getName() + " not " + workspace.getClass().getName());
    }

    public void loadPom() throws ArtifactInitialisationException
    {
        JFileChooser fc = new JFileChooser()
        {
            public void updateUI()
            {
                // workaround for bug http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6317789
                putClientProperty("FileChooser.useShellFolder", Boolean.FALSE);
                super.updateUI();
            }
        };
        fc.setCurrentDirectory(localDiskWorkspace().getWorkspaceDirectory());
        fc.setFileFilter(new FileFilter()
        {

            public boolean accept(File f)
            {
                return f.isDirectory() || "pom.xml".equals(f.getName());
            }

            public String getDescription()
            {
                return "Maven 2 pom files";
            }

        });
        int returnVal = fc.showOpenDialog(frame);
        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            File file = fc.getSelectedFile();
            localDiskWorkspace().loadRootPom(file);
        }
    }

    public RootPom getRoot()
    {
        return workspace.getRoot();
    }

    public void reloadPom() throws ArtifactInitialisationException
    {
        workspace.reloadPomFile();
    }

}
